package sz.szsmk.citizencard.ui.activity;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.view.ViewCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chenenyu.router.annotation.Route;
import com.google.android.flexbox.FlexboxLayout;
import com.gyf.immersionbar.ImmersionBar;

import java.util.ArrayList;
import java.util.List;

import sz.szsmk.citizencard.BuildConfig;
import sz.szsmk.citizencard.DaggerApplication;
import sz.szsmk.citizencard.R;
import sz.szsmk.citizencard.databinding.SearchHotActivityBinding;
import sz.szsmk.citizencard.db.SearchHistory;
import sz.szsmk.citizencard.db.SearchHistoryDao;
import sz.szsmk.citizencard.dialog.TwoButtonDialog;
import sz.szsmk.citizencard.ioc.Compontent.DaggerCommonActivityComponent;
import sz.szsmk.citizencard.log.L;
import sz.szsmk.citizencard.model.network.bean.Book;
import sz.szsmk.citizencard.model.network.bean.response.HotRes;
import sz.szsmk.citizencard.model.network.bean.response.RecommendRes;
import sz.szsmk.citizencard.mvp.contract.ISearchHotContact;
import sz.szsmk.citizencard.mvp.presenter.SearchHotPresenter;
import sz.szsmk.citizencard.ui.adapter.HotSearchAdapter;
import sz.szsmk.citizencard.ui.base.IBaseActivity;
import sz.szsmk.citizencard.util.ACache;
import sz.szsmk.citizencard.util.AndroidDeviceInfo;
import sz.szsmk.citizencard.util.Constant;
import sz.szsmk.citizencard.util.JumpUtils;
import sz.szsmk.citizencard.util.Util;
import sz.szsmk.citizencard.util.zxyh.CheckContentUtil;

/**
 * Copyright (c)2019
 * author: zdh
 * created on: 2019/1/11 14:06
 * description:
 */
@Route("SearchHotActivity")
public class SearchHotActivity extends IBaseActivity<SearchHotPresenter, SearchHotActivityBinding>
        implements ISearchHotContact.ISearchHotView {

    RecyclerView recommendRv;
    RecyclerView hotRv;
    EditText searchEt;
    TextView cancelTv;
    ImageView clear;

    private ArrayList<String> result = new ArrayList<>();
    private ArrayList<String> hotList = new ArrayList<>();
    private HotSearchAdapter adapter;
    private HotSearchAdapter hotAdapter;
    private FlexboxLayout flexboxLayout;
    private SearchHistoryDao searchHistoryDao;
    private List<SearchHistory> searchHistoryDaos;
    private int service;
    @Override
    protected int attachLayoutRes() {
        return R.layout.search_hot_activity;
    }

    @Override
    protected void initInjector() {
        DaggerCommonActivityComponent.builder().appCompontent(DaggerApplication.getAppComponent())
                .build().inject(this);
    }
    @Override
    public void initSystemBar(){
        ImmersionBar.with(this)
                .fitsSystemWindows(true)
                .statusBarDarkFont(true, 0f)
                .statusBarColor(R.color.color_F8FAFD).init();
    }
    @Override
    protected void initViews() {

        recommendRv = findViewById(R.id.recommend_rv);

        hotRv = findViewById(R.id.hot_rv);

        searchEt = findViewById(R.id.search_et);

        cancelTv = findViewById(R.id.cancel_tv);

        clear = findViewById(R.id.news_clear_icon);


        mPresenter.getRecom("地铁");
        mPresenter.getHot();
        service = getIntent().getIntExtra("service",0);
        dataBinding.titleLayout.settingTitle.setText("热门推荐");
        dataBinding.backView.setOnClickListener(v -> {
            finish();
        });
        dataBinding.titleLayout.back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        dataBinding.balanceDelall.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                showDelDialog();
                searchHistoryDao.deleteAll();
                reFreshData();
            }
        });
        dataBinding.searchEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                CheckContentUtil.checkSearchContent(SearchHotActivity.this,dataBinding.cancelTv,dataBinding.searchEt);
            }
        });
        cancelTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                search();
            }
        });
        clear.setOnClickListener(v ->{
            searchEt.setText("");
        });
        flexboxLayout = dataBinding.flexboxLayout;
        searchHistoryDao = DaggerApplication.getmDaoSession().getSearchHistoryDao();
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);
        adapter = new HotSearchAdapter(this);
        adapter.GhfOnClick(new HotSearchAdapter.GhfInterface() {
            @Override
            public void onClick(View view, String data, int position) {
//                Toast.makeText(SearchHotActivity.this, data, Toast.LENGTH_SHORT).show();

                searchHistoryDaos = searchHistoryDao.loadAll();
                int i = 0;
                for (i = 0; i < searchHistoryDaos.size(); i++) {
                    String cardNo = searchHistoryDaos.get(i).getHistory();
                    if (cardNo.equals(data)) {
                        break;
                    }
                }

                if (i == searchHistoryDaos.size()) {
                    SearchHistory sh = new SearchHistory(null, data);
                    searchHistoryDao.insert(sh);
                }
                reFreshData();
                Bundle bundle = new Bundle();
                bundle.putString(Constant.TYPE, data);
                bundle.putInt("service",service);

                JumpUtils.jumptoNatvie(SearchHotActivity.this, "SearchAllActivity", 0, bundle);
            }
        });
        recommendRv.setLayoutManager(gridLayoutManager);
        recommendRv.setAdapter(adapter);

        GridLayoutManager manager = new GridLayoutManager(this, 2);
        hotAdapter = new HotSearchAdapter(this);
        hotAdapter.GhfOnClick(new HotSearchAdapter.GhfInterface() {
            @Override
            public void onClick(View view, String data, int position) {
                searchHistoryDaos = searchHistoryDao.loadAll();
                int i = 0;
                for (i = 0; i < searchHistoryDaos.size(); i++) {
                    String cardNo = searchHistoryDaos.get(i).getHistory();
                    if (cardNo.equals(data)) {
                        break;
                    }
                }

                if (i == searchHistoryDaos.size()) {
                    SearchHistory sh = new SearchHistory(null, data);
                    searchHistoryDao.insert(sh);
                }
                reFreshData();
                Bundle bundle = new Bundle();
                bundle.putString(Constant.TYPE, data);
                bundle.putInt("service",service);
                JumpUtils.jumptoNatvie(SearchHotActivity.this, "SearchAllActivity", 0, bundle);
            }
        });
        recommendRv.setLayoutManager(manager);
        recommendRv.setAdapter(hotAdapter);

        searchEt.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
                    search();
                }
                return false;
            }
        });

        reFreshData();
    }

    private void showDelDialog() {
        final TwoButtonDialog dialog = new TwoButtonDialog(this, "确认删除历史记录吗");
        dialog.setOnOkClickListener(new TwoButtonDialog.OnOkClickListener() {
            @Override
            public void onOkClick() {

                dialog.cancel();
            }
        });
        dialog.setOnCancelClickListener(new TwoButtonDialog.OnCancelClickListener() {
            @Override
            public void onCancelClick() {
                searchHistoryDao.deleteAll();
                dialog.cancel();
                reFreshData();
            }
        });
        dialog.show();
    }

    private TextView createNewFlexItemTextView(final Book book) {
        final TextView textView = new TextView(this);
        textView.setGravity(Gravity.CENTER);
        textView.setText(book.getName());
        textView.setTextSize(12);
        textView.setTextColor(getResources().getColor(R.color.color_99a3a8));
        textView.setBackgroundResource(R.drawable.item_search_back1 );

        textView.setTag(book.getName());
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.e(Constant.TAG, book.getName());
            }
        });
        int paddingBottom = Util.dpToPixel(this, 8);
        int paddingTop = Util.dpToPixel(this, 12);
        int paddingLeft = Util.dpToPixel(this, 8);
        int paddingRight = Util.dpToPixel(this, 16);
        ViewCompat.setPaddingRelative(textView, paddingLeft, paddingTop, paddingRight, paddingBottom);
        textView.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL);
        FlexboxLayout.LayoutParams layoutParams = new FlexboxLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        int margin = Util.dpToPixel(this, 6);
        int marginTop = Util.dpToPixel(this, 6);
        layoutParams.setMargins(margin, marginTop, margin, 0);
        textView.setLayoutParams(layoutParams);
        textView.setOnTouchListener(new View.OnTouchListener() {

            private String mCard;

            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                    Log.i("zhong", "onTouch: motionEventX : " + motionEvent.getX() + " viewWidth :" + view.getWidth());
                    if (motionEvent.getX() < view.getWidth() - view.getHeight() * 0.6) {
                        mCard = textView.getText().toString();
                        dataBinding.searchEt.setText(mCard);
                        Bundle bundle = new Bundle();
                        bundle.putString(Constant.TYPE, searchEt.getText().toString().trim());
                        bundle.putInt("service",service);
                        JumpUtils.jumptoNatvie(SearchHotActivity.this, "SearchAllActivity", 0, bundle);
                    } else {
                        String cardId = (String) view.getTag();
                        for (SearchHistory dao : searchHistoryDaos) {
                            if (dao.getHistory().equals(cardId)) {
                                searchHistoryDao.delete(dao);

                                break;
                            }
                        }
                        reFreshData();
                    }
                }
                return false;
            }
        });
        return textView;
    }

    public void reFreshData() {
        searchHistoryDaos = searchHistoryDao.loadAll();
        if (searchHistoryDaos != null) {
            flexboxLayout.removeAllViews();
            for (int i = 0; i < this.searchHistoryDaos.size(); i++) {
                String cardNo = searchHistoryDaos.get(i).getHistory() + "";
                L.e(Constant.TAG, "数据库查询：" + cardNo);
                Book model = new Book();
                model.setName(cardNo);
                flexboxLayout.addView(createNewFlexItemTextView(model));
            }
        }
    }

    @Override
    protected void updateViews() {

    }


    @Override
    public void getHotFail(HotRes response) {
        Toast.makeText(this, response.getMessage(), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void getHotSucc(HotRes response) {
        List<String> result = response.getResult();
        hotList.clear();
        for (int i = 0; i < result.size(); i++) {
            hotList.add(result.get(i));
        }
        hotAdapter.setViewData(hotList);
        hotAdapter.notifyDataSetChanged();
    }

    @Override
    public void getRecomSucc(RecommendRes response) {
        result.clear();
        List<String> mList = response.getResult();

        for (int i = 0; i < mList.size(); i++) {
            result.add(mList.get(i));
        }
        adapter.setViewData(result);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void getRecomFail(RecommendRes response) {
        Toast.makeText(this, response.getMessage(), Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
    public void search() {
        if (TextUtils.isEmpty(searchEt.getText().toString().trim())) {
            Toast.makeText(SearchHotActivity.this, "请输入关键词", Toast.LENGTH_SHORT).show();
        } else {

            if(BuildConfig.IS_PRO){
                if((searchEt.getText().toString().trim().toLowerCase().equals("opennfc")&& AndroidDeviceInfo.getPhoneProducer().equals("Xiaomi"))||(searchEt.getText().toString().trim().toLowerCase().equals("opennfc")&& AndroidDeviceInfo.getPhoneProducer().equals("Redmi"))){
                    return ;
                }
                if(searchEt.getText().toString().trim().indexOf("http://")>-1||
                        searchEt.getText().toString().trim().indexOf("https://")>-1 ){
                    Log.i("msg",searchEt.getText().toString());
                    String url1 = searchEt.getText().toString().trim();
                    Bundle bundle = new Bundle();
                    if(url1.indexOf("?")>-1){
                        url1+= "&access_token="+ACache.get( this).getAsString("access_token");
                    }else{
                        url1+= "?access_token="+ACache.get( this).getAsString("access_token");
                    }
                    bundle.putString("url", url1);
                    JumpUtils.jumptoNatvie(this, "webView", 0, bundle);
                    return;
                }
            }

            String etCard = searchEt.getText().toString().trim();
            searchHistoryDaos = searchHistoryDao.loadAll();
            int i = 0;
            for (i = 0; i < searchHistoryDaos.size(); i++) {
                String cardNo = searchHistoryDaos.get(i).getHistory();
                if (cardNo.equals(etCard)) {
                    break;
                }
            }

            if (i == searchHistoryDaos.size()) {
                SearchHistory sh = new SearchHistory(null, etCard);
                searchHistoryDao.insert(sh);
            }
            reFreshData();
            Bundle bundle = new Bundle();
            bundle.putString(Constant.TYPE, searchEt.getText().toString().trim());
            bundle.putInt("service", service);
            JumpUtils.jumptoNatvie(SearchHotActivity.this, "SearchAllActivity", 0, bundle);
        }
    }
}
